<template>
  <el-drawer
    :visible.sync="dialogVisible"
    :wrapper-closable="false"
    :modal="false"
    :title="title"
    direction="ltr"
    @close="handleClose"
  >
    <div class="drawer-content">
      <div style="padding: 0 20px;">
        <FenceCreateForm
          ref="fenceCreateFormRef"
          :fence-type="fenceType"
          :model="formData"
          :selector-options="selectorOptions"
          :is-edit="isEdit"
          @radiusChange="handleRadiusChange"
        />
      </div>

      <div class="btn-group">
        <el-button @click="handleCancel">取消</el-button>
        <el-button
          type="primary"
          :loading="loading"
          @click="handleConfirm"
        >
          确定
        </el-button>
      </div>
    </div>
  </el-drawer>
</template>
<script>
import FenceCreateForm from '@/views/vehicleService/components/fenceCreate/FenceCreateForm.vue'
import { FenceType } from '@/views/vehicleService/components/fenceCreate/index'

export default {
  name: 'FenceCreateDialog',
  components: { FenceCreateForm },
  props: {
    visible: {
      type: Boolean,
      default: false
    },

    fenceType: {
      type: Number,
      default: 1
    },

    title: {
      type: String,
      default: ''
    },

    isEdit: {
      type: Boolean,
      default: false
    },

    model: {
      type: Object,
      default: () => ({})
    },

    selectorOptions: {
      type: Array,
      default: () => []
    },

    loading: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      formData: {
        title: '',
        in_rail_alarm: 0,
        out_rail_alarm: 0,
        imei_list: []
      }
    }
  },
  computed: {
    dialogVisible: {
      get() {
        return this.visible
      },
      set(v) {
        this.$emit('update:visible', v)
      }
    }
  },
  watch: {
    dialogVisible(val) {
      if (val) {
        this.$nextTick(() => {
          this.$refs.fenceCreateFormRef.resetFields()

          this.formData = {
            ...this.model
          }

          if (this.fenceType !== FenceType.CIRCLE) {
            delete this.formData.circular_radius
          }
        })
      }
    }
  },
  methods: {
    async handleConfirm() {
      const valid = await this.$refs.fenceCreateFormRef.validate()

      if (!valid) return
      this.$emit('confirm', this.formData)
    },

    handleCancel() {
      this.$emit('cancel')
      this.$emit('update:visible', false)
    },

    handleClose() {
      this.$emit('cancel')
    },

    handleRadiusChange(e) {
      this.$emit('radiusChange', e)
    }
  }
}
</script>
<style lang="scss" scoped>
.drawer-content {
  height: 100%;
  display: flex;
  flex-direction: column;
  justify-content: space-between;

  .btn-group {
    display: flex;
    justify-content: flex-end;
    padding: 20px;
    border-top: 1px solid #F5F5F5;
  }
}
</style>
